<?php
namespace My\Controller;

use Utuo\BackgroundController;

class UserController extends BackgroundController {
	
	public function _initialize() {
		$this->setControllerTitle('会员管理');
		$this->setActionTitle(array(
				'index' => '会员列表',
				'add' => '添加会员',
				'modify' => '修改会员',
				'recycle' => '回收站'
		));
		$this->setActionNav(array(
				'index',
				'add',
				'recycle'
		));
	}
	
	// 会员列表
	public function indexAction() {
		$this->getUserList(0);
	}

	// 回收站
	public function recycleAction() {
		$this->getUserList(1);
	}
	
	// 添加会员
	public function addAction() {
		C("TOKEN_ON", true);
		$this->display();
	}
	
	// 修改会员
	public function modifyAction() {
		$id = I("id", 0, "intval");
		$user = D("User")->find($id);
		$this->assign("user", $user);
		$this->display();
	}
	
	// 添加会员
	public function addPostAction() {
		$d = D("UserAssociation");
		$dUser = D("User");
		if($dUser->create()) {
			if($id = $dUser->add() and $d->uid = $id) {
				$d->cid = $this->aid;
				$d->add();
				$this->ajaxSuccess();
			}
		}
		$this->ajaxError();
	}
	
	// 修改会员
	public function modifyPostAction() {
		$id = I("id", 0, "intval");
		$User = M("User")->alias("this0")->join("__USER_ASSOCIATION__ this1 on this0.id = this1.uid")->where("this0.id=%d and this1.cid=%d", $id, $this->aid)->find();
		if($User){
			$d = D("User");
			if($d->create() and $d->cid = $this->aid) {
				if(false !== $d->save()) {
					$this->ajaxSuccess();
				}
			}
			$this->ajaxError();
		}
		$this->ajaxSuccess('无权限访问');
	}
	
	// 移除会员
	public function removePostAction() {
		$this->ajaxRemove("UserAssociation");
	}
	
	// 恢复会员
	public function restorePostAction() {
		$this->ajaxRestore("UserAssociation");
	}
	
	// 删除会员
	public function deletePostAction() {
		$this->ajaxDelete("UserAssociation");
	}
	
	// 获得会员列表
	private function getUserList($is_deleted) {
		$p = $this->getPage();
		$pageSize = $this->getPageSize();
		$condition = array(
				"this0.is_deleted" => $is_deleted,
				"this0.cid" => $this->aid
		);
		$d = D("UserAssociation")->alias("this0")->join("__USER__ this1 on this1.id = this0.uid")->where($condition)->field("this0.*, this1.name,this1.nick_name,this1.email");
		$new_d = clone $d;
		$userLists = $d->limit($pageSize)->page($p)->order('this1.id')->select();
		$count = $new_d->count();
		$this->assign("userLists", $userLists);
		$this->showPage($count, $pageSize);
		$this->display();
	}
}